<template>
  <scroll-view :scroll-y="true" class="h-11/12 m-auto w-11/12">
    <uni-forms :modelValue="formData">
      <!-- 即食潜在危险食品使用时间作为公共卫生控制手段的日期 -->
      <uni-card
        title="即食潜在危险食品使用时间作为公共卫生控制手段的日期"
        extra="必填*"
      >
        <uni-forms-item>
          <uni-datetime-picker
            type="date"
            :clear-icon="false"
            v-model="formData.date"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 食物名称 -->
      <uni-card title="食物名称" extra="必填*">
        <uni-forms-item>
          <uni-easyinput v-model="formData.shiWuMingCheng" :disabled="isEdit" />
        </uni-forms-item>
      </uni-card>
      <!-- 食物脱离恰当温度控制时的初始温度 -->
      <uni-card title="食物脱离恰当温度控制时的初始温度" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            :disabled="isEdit"
            v-model="formData.shiWuTuoLiQiaDangWenDuKongZhiShiDeChuShiWenDu"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 热/冷食 -->
      <uni-card title="热/冷食" extra="必填*">
        <uni-forms-item>
          <uni-data-checkbox
            v-model="formData.reHuoLengShi"
            :localdata="reHuoLengShi"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <!-- 展示时间 -->
      <uni-card title="展示时间" extra="必填*">
        <uni-forms-item>
          <view
            @click="zhanShiShiJianDatesPop = true && !isEdit"
            class="border-solid border-gray-300 flex items-center justify-between rounded h-10 border"
          >
            <text class="float-left ml-3">{{ formData.zhanShiShiJian }}</text>
            <uni-icons
              class="float-right font-bold"
              type="arrow-down"
              size="18"
            ></uni-icons>
          </view>
        </uni-forms-item>
      </uni-card>
      <!-- 服务结束/丢弃时间 -->
      <uni-card title="服务结束/丢弃时间" extra="必填*">
        <uni-forms-item>
          <view
            @click="diuQiShiJianDatesPop = true && !isEdit"
            class="border-solid border-gray-300 flex items-center justify-between rounded h-10 border"
          >
            <text class="float-left ml-3">{{ formData.diuQiShiJian }}</text>
            <uni-icons
              class="float-right font-bold"
              type="arrow-down"
              size="18"
            ></uni-icons>
          </view>
        </uni-forms-item>
      </uni-card>
      <!-- 填报人姓名 -->
      <uni-card title="填报人姓名" extra="必填*">
        <uni-forms-item>
          <uni-easyinput
            v-model="formData.tianBaoRenXingMing"
            :disabled="isEdit"
          />
        </uni-forms-item>
      </uni-card>
      <uni-card title="评语" v-show="props.id">
        <uni-easyinput v-model="reviewOpinion" />
      </uni-card>
    </uni-forms>
    <button
      @click="submitForm"
      class="mb-10 w-2/3 rounded-xl"
      style="background-color: #5199ff"
    >
      {{ submitBtnName }}
    </button>
    <ShowConfigComponent
      v-show="!isEdit"
      name="shiJianKongZhi"
      @showFormData="showFormData"
    />
  </scroll-view>
  <!-- 展示时间组件 -->
  <Dates
    v-model:selectedTime="formData.zhanShiShiJian"
    @timeSelected="handleZhanShiShiJian"
    @popType="zhanShiShiJianDatesPop = $event"
    v-if="zhanShiShiJianDatesPop"
  />
  <!-- 丢弃时间组件 -->
  <Dates
    v-model:selectedTime="formData.diuQiShiJian"
    @timeSelected="handleDiuQiShiJian"
    @popType="diuQiShiJianDatesPop = $event"
    v-if="diuQiShiJianDatesPop"
  />
</template>

<script lang="ts" setup>
import {
  getTodayDate,
  splitName,
  compareLoadData,
  transformData,
} from '@/utils/utils';
import { ref } from 'vue';
import Dates from '@/components/Dates/Dates.vue';
import { onLoad } from '@dcloudio/uni-app';
import { createTableById, showTableById, submitTable } from '@/services/write';
import type {
  FormDetail,
  returnSubmitData,
  submitTableData,
  tableDate,
} from '@/services/types/write';
import type { RequestMenuIdList } from '@/services/types/review';
import { submitMenuIdList } from '@/services/review';
// 表格提交信息
const formData = ref({
  date: getTodayDate(), //即食潜在危险食品使用时间作为公共卫生控制手段的日期
  shiWuMingCheng: '', //食物名称
  shiWuTuoLiQiaDangWenDuKongZhiShiDeChuShiWenDu: '', //食物脱离恰当温度控制时的初始温度
  reHuoLengShi: '', //热/冷食
  zhanShiShiJian: '', // 展示时间
  diuQiShiJian: '', // 丢弃时间
  tianBaoRenXingMing: '', // 填报人姓名
});
const props = defineProps({
  value: String,
  id: String,
});
// 评语
const reviewOpinion = ref('');
// 是否可编辑
const isEdit = ref(false);
// 提交按钮名字
const submitBtnName = ref('');
//热/冷食 数据
const reHuoLengShi = [
  { text: '热食', value: '热食' },
  { text: '冷食', value: '冷食' },
];

// 展示时间
const zhanShiShiJianDatesPop = ref(false);
const handleZhanShiShiJian = (time: string) => {
  zhanShiShiJianDatesPop.value = false;
  formData.value.zhanShiShiJian = time;
};
// 丢弃时间
const diuQiShiJianDatesPop = ref(false);
const handleDiuQiShiJian = (time: string) => {
  diuQiShiJianDatesPop.value = false;
  formData.value.diuQiShiJian = time;
};
/**
 * 表格相关数据
 */
const table = () => {
  const tableData = ref<tableDate[]>([]);
  const reportingFormOperateId = ref('');
  // 如果提交按钮等于提交则创建表格
  const createTable = async () => {
    submitBtnName.value = '提交';
    // 创建表格
    uni.showLoading({
      title: '加载中...',
      mask: true,
    });
    const res = await createTableById('8286264342009413632');
    reportingFormOperateId.value = res.reportingFormOperateId;
    tableData.value = res.data;
    uni.hideLoading();
  };
  // 提交表格
  const submitNewTable = (
    reportingFormOperateId: string,
    tableData: tableDate[],
  ): submitTableData => {
    const formDetail = transformData(tableData) as FormDetail[];
    //即食潜在危险食品使用时间作为公共卫生控制手段的日期
    formDetail[0].componentValue = formData.value.date;
    //食物名称
    formDetail[1].componentValue = formData.value.shiWuMingCheng;
    //食物脱离恰当温度控制时的初始温度
    formDetail[2].componentValue =
      formData.value.shiWuTuoLiQiaDangWenDuKongZhiShiDeChuShiWenDu;
    //热/冷食
    formDetail[3].componentValue = formData.value.reHuoLengShi;
    formDetail[3].options.filter((item) => {
      if (splitName(item.optionTitle) === formData.value.reHuoLengShi) {
        item.selected = true;
      }
    });

    // 展示时间
    formDetail[4].componentValue = formData.value.zhanShiShiJian;
    // 丢弃时间
    formDetail[5].componentValue = formData.value.diuQiShiJian;

    // 填报人姓名
    formDetail[6].componentValue = formData.value.tianBaoRenXingMing;
    // 其他数据项
    const submitTable = ref<submitTableData>({
      formDetail: formDetail,
      reportingFormOperateId: reportingFormOperateId,
      status: 1,
      unionMenuId: '8286264342009413632',
    });
    return submitTable.value;
  };
  return {
    createTable,
    tableData,
    reportingFormOperateId,
    submitNewTable,
  };
};
const { createTable, tableData, reportingFormOperateId, submitNewTable } =
  table();
// 根据id展示数据
const showDataById = async (id: string) => {
  uni.showLoading({
    title: '加载中...',
    mask: true,
  });
  const res = await showTableById(id);
  if (res.msg === 'success') {
    //即食潜在危险食品使用时间作为公共卫生控制手段的日期
    formData.value.date = res.data.formDetail[0].componentValue;
    //食物名称
    formData.value.shiWuMingCheng = res.data.formDetail[1].componentValue;
    //食物脱离恰当温度控制时的初始温度
    formData.value.shiWuTuoLiQiaDangWenDuKongZhiShiDeChuShiWenDu =
      res.data.formDetail[2].componentValue;
    //热/冷食
    res.data.formDetail[3].options.filter((item) => {
      if (item.selected) {
        formData.value.reHuoLengShi = splitName(item.optionTitle);
      }
    });
    // 展示时间
    formData.value.zhanShiShiJian = res.data.formDetail[4].componentValue;
    // 丢弃时间
    formData.value.diuQiShiJian = res.data.formDetail[5].componentValue;
    // 填报人姓名
    formData.value.tianBaoRenXingMing = res.data.formDetail[6].componentValue;
    // 评语
    reviewOpinion.value = (
      res.data as returnSubmitData
    ).handleOption.reviewOpinion;
  }
  uni.hideLoading();
};
onLoad(async () => {
  // 判断提交按钮是否等于newTable，
  // 等于newTable则执行创建表格
  if (props.value === 'newTable') {
    createTable();
  } else if (props.id) {
    showDataById(props.id);
    submitBtnName.value = '审批';
    isEdit.value = true;
  }
});
// 提交
const submitForm = () => {
  uni.showModal({
    title: '确认提交？',
    content: '提交后将无法修改，请确认是否提交',
    success: function (res) {
      if (res.confirm) {
        // 等于newTable则执行提交表格
        if (props.value === 'newTable') {
          submitTable(
            submitNewTable(reportingFormOperateId.value, tableData.value),
          ).then((res) => {
            if (res.msg === 'success') {
              uni.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 500,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 500);
            }
          });
        } else if (props.id) {
          // 有id意味查看详情
          const data = ref<RequestMenuIdList>({
            id: props.id,
          });
          submitMenuIdList(data.value, reviewOpinion.value).then((res) => {
            if (res.data === 'success') {
              uni.showToast({
                title: '提交成功',
                icon: 'success',
                duration: 500,
              });
              setTimeout(() => {
                uni.navigateBack({
                  delta: 1,
                });
              }, 500);
            }
          });
        }
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    },
  });
};
// 加载配置
const showFormData = (data: any) => {
  compareLoadData(formData.value, data);
};
</script>

<style lang="scss" scoped>
::v-deep.uni-card {
  .uni-card__header {
    .uni-card__header-extra {
      .uni-card__header-extra-text {
        color: #ff0000;
      }
    }
  }
}
</style>
